package models

import (
	"github.com/zw2582/ginlib"
	"time"
)

type IdData struct {
	Id int `xorm:"pk autoincr"`
	Name string `xorm:"varchar(32) notnull"`
	IdCardNo string `xorm:"varchar(32) notnull unique"`
	CreatedAt time.Time `xorm:"created"`
	UpdatedAt time.Time `xorm:"updated"`
}

func init()  {
	ginlib.XormAddWaitSync(new(IdData))
}

//IdDataGetByIdCardNo 根据idcard获取id信息
func IdDataGetByIdCardNo(idCardNo string) (obj IdData) {
	DB.Where("id_card_no=?", ginlib.Md5encode(idCardNo)).Get(&obj)
	return
}

//IdDataSave 同步id信息
func IdDataSave(name, idCardNo string)  {
	if idCardNo == "" {
		return
	}
	obj := IdDataGetByIdCardNo(idCardNo)
	obj.IdCardNo = ginlib.Md5encode(idCardNo)
	if obj.Name != name && name != "" {
		obj.Name = name
	}
	var err error
	if obj.Id == 0 {
		_, err = DB.Insert(&obj)
	} else {
		_, err = DB.ID(obj.Id).Update(&obj)
	}

	if err != nil {
		panic(err)
	}
}

//IdDataCheck id本地校验
func IdDataCheck(name, idCardNo string) (rc ResultCode) {
	if idCardNo == "" || name == "" {
		return nil
	}

	obj := IdDataGetByIdCardNo(idCardNo)
	if obj.Id == 0 {
		return nil
	}

	if obj.Name == "" {
		return nil
	}

	//超过半个月的也不校验
	//if time.Now().Sub(obj.UpdatedAt) > time.Hour*24*15 {
	//	return nil
	//}

	if obj.Name != name {
		rc = RC_ID_NOT_YIZHI
	} else {
		rc = RC_ID_YIZHI
	}
	return
}